package openase.audiosearch.ranking;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import openase.audio.AudioFingerprint;
import openase.audio.AudioInfo;
import openase.audiosearch.FingerprintMatch;


public class UniqueQueryMatchesRankingStrategy implements RankingStrategy {

    @Override
    public AudioRanking rank(FingerprintMatch[] matchingFps) {
        Map<AudioInfo, Set<AudioFingerprint>> audioQueryUniqueMatches = new HashMap<AudioInfo, Set<AudioFingerprint>>();

        for (FingerprintMatch match: matchingFps) {
            // just add this source to the bag
            AudioInfo source = match.getRepositoryFingerprint().getSource();
            AudioFingerprint fingerprint = match.getQueryFingerprint();
            add(audioQueryUniqueMatches, source, fingerprint);
        }
        
        final AudioRankingBuilder builder = new AudioRankingBuilder();
        
        for (Entry<AudioInfo, Set<AudioFingerprint>> entry : audioQueryUniqueMatches.entrySet()) {
            AudioInfo audio = entry.getKey();
            int rankValue = entry.getValue().size();
            
            builder.add(audio, rankValue);
        }
        
        return builder.getAudioRanking();
    }

    private static void add(Map<AudioInfo, Set<AudioFingerprint>> audioOffsets, AudioInfo source, AudioFingerprint fingerprint) {
        Set<AudioFingerprint> set = audioOffsets.get(source);
        if (set == null) {
            set = new HashSet<AudioFingerprint>();
            audioOffsets.put(source, set);
        }
        set.add(fingerprint);
    }

}
